﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MangaManagerLib;
using System.Text.RegularExpressions;
namespace KissMangaReader
{
    
    [MangaPluginAttribute("get data from kissmanga website")]
    public class KissMangaReader: IMangaOperation
    {
        #region IMangaOperation Members
        private String GetURLHost(string url)
        {
            //startIndex can begin from http://(7) or https:// (8)
            int endHostUrlIndex = url.IndexOf("/", 9);
            string hostURL = url.Substring(0, endHostUrlIndex);
            return hostURL;
        }
        public IList<string> GetDataForChapter(string url)
        {
            IList<string> resultValue = new List<string>();
            string sourceCode = WebWorker.GetContent(url);
            int startIndex = sourceCode.IndexOf("lstImages.push(\"");
            if(startIndex < 1)
            {
                return null;
            }
            sourceCode = sourceCode.Substring(startIndex, sourceCode.Length - startIndex);
            while (sourceCode.IndexOf("lstImages.push(\"") != -1)
            {
                startIndex = sourceCode.IndexOf("lstImages.push(\"") + 16;
                int endIndex = sourceCode.IndexOf("\");", startIndex);
                string link = sourceCode.Substring(startIndex, endIndex - startIndex);
                resultValue.Add(link);
                sourceCode = sourceCode.Replace(string.Format("lstImages.push(\"{0}", link), "");
            }
            return resultValue;
        }

        public MangaStoryDetail GetMangaStoryDetail(string url)
        {
            MangaStoryDetail mangaStoryDetail = new MangaStoryDetail();
            mangaStoryDetail.Chapters = new List<Chapter>();
            string urlHost = GetURLHost(url);
            string sourceCode = WebWorker.GetContent(url).Replace("\r", "").Replace("\n", "").Replace("\t", "");
            string linkRegex = @"<a\s*[\w]*=""bigChar""\s*href=""([\(\)""&/\s\’\%\$\?\[\]\{\}\,\!\@\#\*\d\w:;'=+\-\.\\]*)""[^>]*>([\(\)""&/\s\’\%\$\?\[\]\{\}\,\!\@\#\*\d\w:;'=+\-\.\\]*)</a>";
            Match linkMatch = Regex.Match(sourceCode, linkRegex, RegexOptions.IgnoreCase);

            if (linkMatch.Success)
            {
                mangaStoryDetail.Link = string.Format("{0}{1}", urlHost, linkMatch.Groups[1].Value);
                mangaStoryDetail.Title = linkMatch.Groups[2].Value;
            }
            //get author
            linkRegex = @"Author:</span>&nbsp;<a[\s\w\d""'\.’:;=+%/&?\-]*[^>]*>([/:&’?\w\s\d\-]*)</a>";
            linkMatch = Regex.Match(sourceCode, linkRegex, RegexOptions.IgnoreCase);
            if (linkMatch.Success)
            {
                mangaStoryDetail.Author = linkMatch.Groups[1].Value;
            }
            //get summary
            linkRegex = @"Summary:</span>\s*<p[\s\w\d""'’=+%/&?\-;]*[^>]*>([\(\)""&/\s\’<\>\%\$\?\[\]\{\}\,\!\@\#\*\d\w:;'=+\-\.\\]*)[^(</p>)]</p>";
            linkMatch = Regex.Match(sourceCode, linkRegex, RegexOptions.IgnoreCase);
            if (linkMatch.Success)
            {
                mangaStoryDetail.Summary = linkMatch.Groups[1].Value;
                if (mangaStoryDetail.Summary.Contains("</p>"))
                {
                    int indexNeedRemove = mangaStoryDetail.Summary.IndexOf("</p>");
                    mangaStoryDetail.Summary = RemoveHTMLTag(mangaStoryDetail.Summary.Substring(0, indexNeedRemove));
                }
            }
            linkRegex = @"Image</div>\s*<div[^>]*>\s*<div[\s\w\d""’'=+%/&?\-]*[^>]*>[\s\w\d;’:&]*</div>\s*<div[\s\w\d""'’=+%/&?\-]*[^>]*>\s*<img.*src=""([/\.\s\d\w:;'""=+-]*)""(\s*)/>";
            linkMatch = Regex.Match(sourceCode, linkRegex, RegexOptions.IgnoreCase);
            if (linkMatch.Success)
            {
                mangaStoryDetail.ImageLink = linkMatch.Groups[1].Value;
            }

            string chaptersRegex = @"<td>\s*<a\s*href=""([/\.\s\d\w&%’?'""%=+\-]*)""\s*title=""[\(\)""&/\s\%\$\?\[\]’\{\}\,\!\@\#\*\d\w:;'=+\-\.\\]*""[^>]*\s*>([\(\)""&/\s\%\$\?\[\]\{\}\,\!\@\#\*\d’\w:;'=+\-\.\\]*)</a>\s*</td>\s*<td>\s*(\d*/\d*/\d*)\s*</td>";
            MatchCollection chaptersMatch = Regex.Matches(sourceCode, chaptersRegex, RegexOptions.IgnoreCase);
            foreach (Match m in chaptersMatch)
            {
                Chapter c = new Chapter();
                c.Date = m.Groups[3].Value;
                c.Link = string.Format("{0}{1}", urlHost, m.Groups[1].Value);
                c.Title = m.Groups[2].Value.TrimStart().TrimEnd();
                mangaStoryDetail.Chapters.Add(c);
            }
            return mangaStoryDetail;
        }

        public MangaCollection GetMangaCollection(string url, int page)
        {
            MangaCollection mangaCollection = new MangaCollection();
            mangaCollection.CurrentPage = page;
            mangaCollection.MangaList = new List<MangaStory>();
            string sourceCode = WebWorker.GetContent(string.Format("{0}?page={1}", url, page) );
            string listMangaRegex;
            //listMangaRegex  = @"\<table[a-zA-Z0-9='""\>\<\s\\\[\^\$\.\|\?\*\+\(\)\{\}]*";
            listMangaRegex = @"\<(table)[\W|\w\r\n]*</table>"; 
            Regex listRgx = new Regex(listMangaRegex, RegexOptions.IgnoreCase);
            MatchCollection matches = listRgx.Matches(sourceCode, 0);
            if (matches.Count > 0)
            {
                string tableContain = matches[0].Value;
                string mangaRegex = @"title='\s*<img.*src=""([/\.\s\d\w&?%:'""=+-]*)""\s*style.*/>\s*<div.*>\s*" +
                    @"<a.*href=""([/\.\s\d\w:;&?%""=+-]*)"">(.*)</a>\s*" +
                    @"<p>(.*[\(\)""&/\s\%\$\?\[\]\{\}\,\!\@\#\*\d\w:;'=+\-\.\\]*.*)</p>";
                tableContain = tableContain.Replace("\r", "").Replace("\n", "").Replace("\t", "");              
                Regex mangaRgx = new Regex(mangaRegex, RegexOptions.IgnoreCase);
                MatchCollection mangaMatches = mangaRgx.Matches(sourceCode, 0);
                Console.WriteLine(mangaMatches.Count);
                //produce manga object
                foreach (Match mt in mangaMatches)
                {
                    MangaStory mangaStory = new MangaStory();
                    mangaStory.ImageLink = mt.Groups[1].Value;
                    mangaStory.Link = string.Format("{0}{1}", GetURLHost(url), mt.Groups[2].Value);
                    mangaStory.Title = mt.Groups[3].Value;
                    mangaStory.Summary = RemoveHTMLTag(mt.Groups[4].Value.Replace("\r", "").Replace("\n", "").Replace("\t", "") ).TrimStart().TrimEnd();
                    mangaCollection.MangaList.Add(mangaStory);
                }

            }
            string lastPageRegex = @"page=[""]*([\d]*)[""]*[^>]*>[&\d\w\s;:]*Last\s*</a>";
            Regex lastPageRgx = new Regex(lastPageRegex, RegexOptions.IgnoreCase);
            Match lastPageMatch = lastPageRgx.Match(sourceCode, 0);
            if (lastPageMatch.Success)
            {
                try
                {
                    mangaCollection.TotalPage = int.Parse(lastPageMatch.Groups[1].Value);
                }
                catch (Exception ex)
                {
                    Logger.GetInstance().LogException(ex);
                }
            }
            return mangaCollection;
        }
        private string RemoveHTMLTag(string s)
        {
            string result;
            string htmlregex = @"<([/\.\s\d\w&?%:'""=+-]*)[^>]*>";
            s.Replace("\r", "").Replace("\n", "").Replace("\t", "").TrimStart().TrimEnd();
            MatchCollection matches = Regex.Matches(s,  htmlregex, RegexOptions.IgnoreCase);
            foreach (Match m in matches)
            {
                s = s.Replace(m.Value, string.Empty);
            }
            result = s; 
            return result;
        }
        
        #endregion
    }
}
